package com.itheima.ui;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ClientThread extends Thread {

    private Socket socket;

    private  DataInputStream dis;

    private ClientChatFrame win;

    public ClientThread(Socket socket, ClientChatFrame win) {
        this.socket = socket;
        this.win = win;
    }

    @Override
    public void run() {

        //接收的消息有3种：1.在线人数更新消息，2.群聊消息
        try {
            dis = new DataInputStream(socket.getInputStream());
            while (true) {
                int type = dis.readInt();
                switch (type) {
                    case 1:
                        //服务端发来了在线人数更新消息，更新全部客户端的在线人数列表
                        updateClientOnlineUserList();
                        break;

                    case 2:
                        //服务端发来了群聊消息，接下来要接收消息内容
                        getMessageToWin();

                        break;
                    case 3:
                        break;

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getMessageToWin() throws Exception {
        //接收消息内容
        String msg = dis.readUTF();
        win.setMessageToWin(msg);
    }

    private void updateClientOnlineUserList() throws Exception {
        //更新全部客户端的在线人数列表

        //1.读取有多少个在线用户
        int count = dis.readInt();

        //2.循环控制读取每个用户的昵称，放到集合中
        List<String> onlineNicknames = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            String nickname = dis.readUTF();
            onlineNicknames.add(nickname);
        }

        //3.将集合中的昵称数据展示在聊天界面中
        win.updateOnlineUserList(onlineNicknames);



    }

}
